﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace Gateway.UI.Api.Filters
{
    /// <summary>
    /// 参数校验
    /// </summary>
    public class ModelValidateActionFilterAttribute : IAsyncActionFilter
    {


        /// <summary>
        /// 
        /// </summary>
        public ModelValidateActionFilterAttribute()
        {
         
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //模型验证不通过
            if (!context.ModelState.IsValid)
            {
                ApiResult result = new ApiResult(SystemErrorCode.ModelValidateError);
                result.Message += ":";
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        result.Message += $"{error.ErrorMessage}|";
                    }
                }

                result.Message = result.Message.TrimEnd('|');
                context.Result = new JsonResult(result);
                return;
            }
            await next();
        }
    }
}